
import {observable,action} from 'mobx-miniprogram'
import Tim from '../model/tim'
import TIM from 'tim-wx-sdk-ws'


export const timStore = observable({


  // 数据字段
  sdkReady:false,
  messageList:[],
  _targetUserId:null,

  login:action(function(){
    this._runLitener()
    const res = Tim.getInstance().login()
   console.log(res)
  }),

  logout:action(function(){
    Tim.getInstance().logout()
  }),





  // 监听事件
  _runLitener(){
    
    const sdk= Tim.getInstance().getSDK()
    sdk.on(TIM.EVENT.SDK_READY,this._handleSDKReady,this)
    sdk.on(TIM.EVENT.SDK_NOT_READY, this._handleSDKNotReady,this)
    sdk.on(TIM.EVENT.KICKED_OUT, this._handleSDKNotReady,this)
    sdk.on(TIM.EVENT.MESSAGE_RECEIVED, this._handleMessageReceived,this)
  },


  // 主动拉取
   getMessageList:action(async function(){
    if(!this._targetUserId){
      throw Error('未指定目标用户ID')
    }

    this.messageList = await Tim.getInstance().reset().getMessageList(this._targetUserId)
    // 消息已读
    Tim.getInstance().setMessageRead(this._targetUserId)
  }),

  // 有消息来就触发
  async _handleMessageReceived(event){
    if(!this._targetUserId){
      throw Error('未指定目标用户ID')
    }
    const currentConversationMessage = event.data.filter(item => item.form === this._targetUserId)
    if(currentConversationMessage.length){
      this.messageList = this.messageList.concat(currentConversationMessage)
      Tim.getInstance().setMessageRead(this._targetUserId)
    }
  },

  setTargetUserId:action(function(targetUserId){
    this._targetUserId = targetUserId
  }),

  _handleSDKReady(){
    console.log(123)
    this.sdkReady = true
  },
  _handleSDKNotReady(){
    console.log(456)
    this.sdkReady = false
  },
  _handleKickedout(){

  }
})